/**
 * @name: server.ts
 * @author: XU>.<CHEN
 * @date: 2022-05-24 20:42
 * @description：server.ts
 * @update: 2022-05-24 20:42
 */
import express, {Application} from 'express'
import jwt from 'jsonwebtoken'
import bodyParser from "body-parser";
import cookieParser from 'cookie-parser'

// dto
import db, { connect } from './db/config'
import ResponseMessage from "./utils/ResponseMessage";

// routers
import user from './routes/user'
import routeIndex from './routes/routeIndex'

const app: Application = express()
const R = new ResponseMessage()
const port = 3000

const whiteRoutes = ['/user/login', '/'] // 无需token验证的请求
const secretOrPublicKey = 'blackSide' // jwt加密盐值

app.use(cookieParser()) // 使用 cookie插件

// body解析中间件 post请求必须有
app.use(bodyParser.urlencoded({ extended: true })) // application/x-www-form-urlencoded
app.use(bodyParser.json()) // application/json


// 全局请求拦截 token鉴权
app.use((req, res, next) => {
  const { url, headers: { authorization: token } } = req
  if (whiteRoutes.indexOf(url) !== -1) return next()

  if (!token) return res.json(R.error('token不存在'))
  jwt.verify(token, secretOrPublicKey, (err:any , data: any) => {
    if (err && err.message === 'invalid token') return res.json(R.error('token验证失败'))
    if (err && err.message === 'jwt expired') return res.json(R.error('token已失效'))
    // @ts-ignore
    globalThis.userInfo = data
  })
  next()
})

// 加载接口路由表
app.use('/', routeIndex)
app.use('/user', user)

// 连接数据库
connect()

app.listen(port, () => {
  console.log('servers is running on http://localhost:3000/')
})
module.exports = app;